/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

<template>
  <div class='game' ref='gameContainer'>
    <!-- 按钮组 -->
    <div class='button-group' :style='{
      marginTop: `${topMargin + 8}px`,
      marginLeft: `${(topMargin ? 0 : margins.leftTopMargin) + 16}px`,
      marginRight: `${(topMargin ? 0 : margins.rightTopMargin) + 16}px`
    }'>
      <!-- 顶部按钮 -->
      <div class='top-buttons' :style="{ width: !needChangeView ? '100%' : 'auto' }">
        <img :src='topButtons[0]' class='button-image'>
        <!-- 中间空白填充 -->
        <div v-if='needChangeView' class='center-blank'></div>
        <img v-if='rowNum > 6 && !needChangeView' src='../assets/stars.png' alt='' :style="{ height: '54px' }" />
        <img :src='topButtons[1]' class='button-image'>
      </div>

      <!-- 中间空白填充 -->
      <div v-if='needChangeView' class='center-blank'></div>

      <!-- 侧边按钮 -->
      <div v-if='needChangeView' class='bottom-buttons'>
        <img :src='bottomButtons[0]' class='button-image'>
        <img :src='bottomButtons[1]' class='button-image'>
        <img :src='bottomButtons[2]' class='button-image'>
      </div>
    </div>

    <!-- 中间网格容器 -->
    <div class='grid-container' :style="{
      paddingLeft: needChangeView ? `${margins.leftBottomMargin || margins.leftCenterMargin + 16}px` : `${margins.leftCenterMargin + 16}px`,
      paddingRight: needChangeView ? `${margins.rightBottomMargin || margins.rightCenterMargin + 16}px` : `${margins.rightCenterMargin + 16}px`,
      gridTemplateColumns: `repeat(${rowNum}, minmax(68px, 72px))`,
      gridAutoRows: 'minmax(68px, 72px)'
    }">
      <div v-for='(item, index) in gridItems' :key='index' class='grid-item'>
        <img :src='item' class='grid-image'>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div v-if='!needChangeView' class='bottom-buttons' :style='{
      marginLeft: `${(bottomMargin ? 0 : margins.leftBottomMargin) + 16}px`,
      marginRight: `${(bottomMargin ? 0 : margins.rightBottomMargin) + 16}px`,
      marginBottom: `${bottomMargin + 12}px`
    }'>
      <img :src='bottomButtons[0]' class='button-image'>
      <div class='bottomRight-buttons'>
        <img :src='bottomButtons[1]' class='button-image'>
        <img :src='bottomButtons[2]' class='button-image'>
      </div>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import { topButtons, gridImages, bottomButtons } from '../common/ResPath';
import { AreaUtils } from '../utils/AreaUtils';
import { AvoidAreaType } from '../common/windowCommon';

const TAG = 'GAMEPAGE:';

const topMargin = ref(AreaUtils.getInstance().getTopMargin());
const bottomMargin = ref(AreaUtils.getInstance().getBottomMargin());
const margins = reactive({
  leftTopMargin: 0,
  rightTopMargin: 0,
  leftBottomMargin: 0,
  rightBottomMargin: 0,
  leftCenterMargin: 0,
  rightCenterMargin: 0
});
const needChangeView = ref(false);
const rowNum = ref(4);
const columnNum = ref(8);
const gridItems = ref(gridImages);
const gameContainer = ref<HTMLElement | null>(null);

const reCulcAvoidArea = (): void => {
  AreaUtils.getAvoidAreaLocation().then((res) => {
    AreaUtils.getInstance().setAvoidValue(res.areaLocation, res.marginValue);
    Object.assign(margins, AreaUtils.getAllMargin());
    needChangeView.value = AreaUtils.checkIfNeedChangeView();
  });
};

const calculateGridItemNum = (): void => {
  if (gameContainer.value) {
    const game = gameContainer.value;
    const itemSize = 72; // 每个 grid-item 的大小
    const margin = 6; // 每个 grid-item 的外边距
    const topHeight = 76;
    const bottomHeight = 63;
    const sideWidth = 4;

    // 计算容器宽高
    const gridWidth = Number(getComputedStyle(game).getPropertyValue('width').replace('px', ''));
    const gridHeight = Number(getComputedStyle(game).getPropertyValue('height').replace('px', ''));

    // 计算左右边距和容器可用高度
    let leftMargin;
    let rightMargin;
    let availableHeight = gridHeight - topHeight;
    if (needChangeView.value) {
      leftMargin = margins.leftBottomMargin || margins.leftCenterMargin + sideWidth;
      rightMargin = margins.rightBottomMargin || margins.rightCenterMargin + sideWidth;
      availableHeight -= bottomHeight;
    } else {
      leftMargin = margins.leftCenterMargin + sideWidth;
      rightMargin = margins.rightCenterMargin + sideWidth;
    }

    // 计算网格数量
    rowNum.value = Math.floor((gridWidth - leftMargin - rightMargin) / (itemSize + 2 * margin));
    columnNum.value = Math.round(availableHeight / (itemSize + 2 * margin));
    const totalNum = rowNum.value * columnNum.value;
    const randomItems = [];
    for (let i = 0; i < totalNum; i++) {
      const randomIndex = Math.floor(Math.random() * gridImages.length);
      randomItems.push(gridImages[randomIndex]);
    }
    gridItems.value = randomItems;
  }
};

const handleStatusBarChange = (event: any): void => {
  console.debug(TAG, `statusBarChange data is ${JSON.stringify(event.detail)}`);
  const data = event.detail;
  const areaType = data.type;
  reCulcAvoidArea();
  if (areaType === AvoidAreaType.TYPE_SYSTEM) {
    topMargin.value = AreaUtils.px2vp(data.area.topRect.height);
    AreaUtils.getInstance().setTopMargin(topMargin.value);
  }
  if (areaType === AvoidAreaType.TYPE_CUTOUT) {
    calculateGridItemNum();
  }
  if (areaType === AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
    bottomMargin.value = AreaUtils.px2vp(data.area.bottomRect.height);
    AreaUtils.getInstance().setBottomMargin(bottomMargin.value);
  }
};

onMounted(() => {
  reCulcAvoidArea();
  calculateGridItemNum();
  window.addEventListener('resize', calculateGridItemNum);
  window.addEventListener('statusBarChange', handleStatusBarChange);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', reCulcAvoidArea);
  window.removeEventListener('statusBarChange', handleStatusBarChange);
});
</script>

<style scoped>
.game {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-image: url('../assets/game_background.png');
  background-size: auto 100%;
  background-position: left;
  background-attachment: fixed;
}

.top-buttons {
  display: flex;
  height: 76px;
  gap: 20px;
  justify-content: space-between;
  align-items: center;
}

.bottom-buttons {
  display: flex;
  height: 63px;
  gap: 20px;
  justify-content: space-between;
}

.button-image {
  object-fit: auto;
  height: 100%;
}

.center-blank {
  width: 100%;
  height: 100%;
}

.button-group {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.grid-container {
  display: grid;
  gap: 12px;
  overflow-y: auto;
  scrollbar-width: 0;
  justify-content: center;
  margin-bottom: 15px;
  margin-top: 15px;
}

.grid-item {
  width: 100%;
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: url('../assets/bird_bg.svg');
  background-size: contain;
  background-position: center;
}

.grid-image {
  width: 100%;
  height: 55px;
  object-fit: Contain;
}

.bottomRight-buttons {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 20px;
}

/* 横屏适配 */
@media (orientation: landscape) {
  .button-group {
    display: flex;
    justify-content: space-between;
    flex-direction: row;
  }
}
</style>
